<!--预约规则配置-->
<template>
  <div
    class="ky-container container"
    @click="handleCancel">
    <div>
      <el-card shadow="hover" class="ky-card-xs ky-card-hdbg">
        <el-form :inline="true" class="ky-form-inline ky-form-inline-sm" label-width="140px" size="small">
          <el-row>
            <el-col>
              <el-form-item label="医院名称" prop="hospitalCode">
                <el-select size="small" class="param-type_input" v-model="listQuery.hospitalCode" placeholder="请选择" filterable @change="handleChange('hospital')">
                  <el-option
                    v-for="(item,index) in mx_hospitalList"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="院区名称">
                <el-select size="small" style="width: 215px;" class="param-type_input" v-model="listQuery.areaName" placeholder="请选择" clearable collapse-tags @change="handleChange('areaName')">
                  <el-option
                    v-for="(item,index) in areaNameOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="影像区域">
                <el-select size="small" style="width: 215px;" class="param-type_input" v-model="listQuery.depArea" placeholder="请选择" clearable collapse-tags @change="handleChange('depArea')">
                  <el-option
                    v-for="(item,index) in depAreaOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="检查部门">
                <el-select size="small" style="width: 215px;" class="param-type_input" v-model="listQuery.dep" placeholder="请选择" clearable collapse-tags @change="handleChange('dep')">
                  <el-option
                    v-for="(item,index) in depOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="检查机房">
                <el-select size="small" style="width: 215px;" class="param-type_input" v-model="listQuery.checkRoom" filterable placeholder="请选择" clearable collapse-tags>
                  <el-option
                    v-for="(item,index) in checkRoomOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="检查部位">
                <el-select size="small" style="width: 215px;" v-model="listQuery.bigpart" placeholder="请选择" filterable clearable collapse-tags @change="handleChange('bigpart')">
                  <el-option
                    v-for="(item,index) in bigpartOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="检查项目">
                <virtualselect
                  :data="smallpartOptions"
                  v-model="listQuery.smallpart"
                  placeholder="请选择"
                  clearable
                  @change="handleChange('smallpart')"
                ></virtualselect>
              </el-form-item>
              <el-form-item label="患者类型">
                <el-select size="small" style="width: 215px;" class="param-type_input" v-model="listQuery.patientType" placeholder="请选择" clearable>
                  <el-option
                    v-for="(item,index) in patientTypeOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="项目属性" prop="itemProperty">
                <el-select
                  style="width: 100%"
                  size="small"
                  filterable
                  allow-create
                  v-model="listQuery.itemProperty"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in itempropertyOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="预约来源">
                <el-select size="small" style="width: 215px;" class="param-type_input" v-model="listQuery.appointmentType" placeholder="请选择" clearable>
                  <el-option
                    v-for="(item,index) in appointmentTypeOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="规则名称">
                <el-input size="small" class="param-name_input" v-model="listQuery.ruleName" placeholder="搜索规则名称/描述/提醒" clearable @change="search"></el-input>
              </el-form-item>
              <el-form-item label="规则类型">
                <el-select size="small" class="param-type_input" v-model="listQuery.ruleType" multiple placeholder="请选择规则类型" clearable collapse-tags @change="search">
                  <el-option
                    v-for="item in options.ruleTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="规则状态">
                <el-select size="small" class="param-type_input" v-model="listQuery.status" placeholder="请选择规则状态" @change="search">
                  <el-option
                    v-for="item in options.ruleStatusQueryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- 支持关联规则检查类型表--、大部位、小部位查询 -->
              <!-- 支持关联规则条件表--院区名称、影像区域,检查部门、检查机房、预约来源、项目属性、患者类型查询--等web更新后支持 -->
              <el-form-item>
                <el-button type="primary" class="m-l-0 click-button" icon="el-icon-search" size="small" @click="search">查询</el-button>
                <el-button class="m-l-0 click-button" size="small" @click="resetParam" plain>重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <!-- <header>规则配置</header> -->
      <el-card shadow="hover" class="ky-card-xs ky-card-hdbg ky-mt10">
        <section class="content-section p-0">
          <div class="content-title flex flex-row justify-between">
            <div>
              <span>预约规则列表</span>
              <el-button class="ky-ml20" type="primary" size="small" icon="el-icon-monitor" @click="handleDicDialog">规则数据字典管理</el-button>
              <el-button v-permission="'YJYY10002004'" type="primary" size="small" icon="el-icon-plus" @click.stop="getRightPanel(pageStatus.add)">新增规则</el-button>
              <el-button v-permission="'YJYY10002004'" type="primary" size="small" icon="el-icon-plus" @click.stop="setPanelDefault(pageStatus.add)">时段条件规则</el-button>
              <el-button type="text" size="small" @click="openHelper" icon="el-icon-document">帮助说明</el-button>
              <el-button type="text" size="small" @click="ruleIntroDialog=true" icon="el-icon-document">规则说明</el-button>
            </div>
            <div>
              <el-button class="" v-if="batchUpdateAppoScale" type="primary" size="small" icon="el-icon-monitor" @click="handleSetRoom">批量维护号源比例</el-button>
            </div>
          </div>
          <el-row>
            <el-col :span="24" class="col-left">
              <el-table
                ref="table"
                v-loading="loading"
                size="medium"
                :data="tableData"
                style="width: 100%"
                border
                @selection-change="handleSelectionChange"
                class="ky-table"
                highlight-current-row
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column align="left" label="操作" width="256" v-if="$hasPermission(['YJYY10002003','YJYY10002005','YJYY10002006'])">
                  <template slot-scope="scope">
                    <div class="flex flex-row justify-center text-center">
                      <el-button type="primary" size="small" @click.stop="getRightPanel(pageStatus.edit,scope.row)" v-permission="'YJYY10002003'"><i class="el-icon-edit"></i> 编辑</el-button>
                      <el-button type="danger" size="small" @click.stop="handleDelete(scope.$index, scope.row)" v-permission="'YJYY10002005'"><i class="el-icon-delete"></i> 删除</el-button>
                      <el-button :type="scope.row.status ? 'warning':'success'" size="small" @click="handleLock(scope.row)" v-permission="'YJYY10002006'"><i :class="scope.row.status ? 'el-icon-lock':'el-icon-unlock'"></i> {{scope.row.status ? '禁用' : '启用'}}</el-button>
                    </div>
                  </template>
                </el-table-column>
                <!-- <el-table-column align="left" prop="hospitalCode" label="医院名称" :formatter="frtHospCode"> </el-table-column> -->
                <el-table-column align="left" prop="ruleName" label="规则名称" width="238">
                  <template slot-scope="scope">
                    <span v-if="scope.row.ruleType === 10" style="cursor:pointer;text-decoration: underline;" @click="openInfoDialog(scope.row.hospitalCode,scope.row.id)">
                      {{`${ruleTypeFlr(scope.row.ruleType)}-${scope.row.ruleName}`}}
                    </span>
                    <span v-else>
                      {{`${ruleTypeFlr(scope.row.ruleType)}-${scope.row.ruleName}`}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column align="left" prop="ruleDescribe" label="规则描述" width="220" show-overflow-tooltip></el-table-column>
                <el-table-column align="left" prop="ruleType" label="规则类型" width="110">
                  <template slot-scope="scope">{{scope.row.ruleType | ruleTypeFlr}}</template>
                </el-table-column>
                <el-table-column align="left" prop="priority" label="优先级" width="75"></el-table-column>
                <el-table-column align="left" prop="status" label="规则状态" width="100">
                  <template slot-scope="scope">
                    <span :class="!scope.row.status ? 'warning-color':'success-color'">
                      {{scope.row.status | ruleStatusFlr}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column align="left" prop="ruleMessage" label="规则提醒" width="220" show-overflow-tooltip></el-table-column>
                <el-table-column align="left" prop="hospitalName" label="医院名称" width="210">
                  <template slot-scope="scope">{{scope.row.hospitalCode | hospitalCodeFlr(mx_hospitalList)}}</template>
                </el-table-column>
                <el-table-column align="left" prop="createTime" label="创建时间" width="160"></el-table-column>
                <el-table-column align="left" prop="updateTime" label="更新时间" width="160"></el-table-column>
                <!-- <el-table-column align="left" prop="itemProperty" label="项目属性" min-width="160"></el-table-column> -->
              </el-table>
              <paginationCont
                :total="totalCount"
                :page.sync="currentPage"
                :limit.sync="pageSize"
                @pagination="fetchData"
              />
            </el-col>
          </el-row>
          <dic-dialog :dialog-dic-visible="dialogDicVisible" @myClose="handleDicClose" :hospital-code="listQuery.hospitalCode"></dic-dialog>
          <!-- <setRoomDialog :dialog-dic-visible="dialogSetRoomVisible" @myClose="dialogSetRoomVisible = false" :check-room-options="checkRoomOptions" :hospital-code="listQuery.hospitalCode"></setRoomDialog> -->
          <template-fullschedule-dialog
            ref="templatefullscheduledialog"
            :all-checkbox="true"
            :appo-repair="appoRepair"
            :check-room-options="checkRoomOptions"
            :hospital-code="listQuery.hospitalCode"
          ></template-fullschedule-dialog>
        </section>
      </el-card>
      <transition name="fade-form" mode="out-in">
        <div :class="{'toolBox-small':device !== 'mobile' && sidebar.opened,'toolBox-midul': device !== 'mobile' && !sidebar.opened,'toolBox-large':device == 'mobile','toolBox':true}" v-show="showToolBox">
          <div>
            <i class="el-icon-info icon blue-color"></i>
            <span class="toolBox-text">已选择<span class="blue-color">{{multipleSelection.length}}</span>项</span>
            <span class="cancle-click" @click="cancleChoose">取消选择</span>
          </div>
          <div>
            <el-button type="warning" size="small" v-if="qiyongFlag&&!jingyongFlag" @click="batchSetStatus" v-permission="'YJYY10002006'">批量禁用</el-button>
            <el-button type="success" size="small" v-else-if="!qiyongFlag&&jingyongFlag" @click="batchSetStatus" v-permission="'YJYY10002006'">批量启用</el-button>
            <el-button type="danger" size="small" @click="batchDelete" v-permission="'YJYY10002005'">批量删除</el-button>
          </div>
        </div>
      </transition>
    </div>
    <!-- 规则模块 -->
    <settingDialog
      ref="settingDialog"
      :visible.sync="showRight"
      :row-data.sync="rowData"
      :cur-status="curStatus"
      :hospital-code="listQuery.hospitalCode"
      @refresh="settingRefresh"
      @openSourceInfo="openInfoDialog"></settingDialog>
    <sourceInfoDialog ref="sourceInfoDialog" :visible.sync="infoVisible" :hospital-code="infoParams.hospitalCode" :rule-info-id="infoParams.id"></sourceInfoDialog>
    <el-dialog
      class="notify-dialog"
      title="预约规则流程说明"
      width="80%"
      top="5vh"
      :destroy-on-close="true"
      :visible.sync="dialogVisible"
    >
      <!-- <div ref="docxFile"></div> -->
      <iframe src="/static/file/ruleDescription.pdf" width="100%" frameborder="0"/>
      <!--  <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="download"
        >下 载</el-button
        >
      </span> -->
    </el-dialog>

    <el-dialog
      title="规则说明"
      width="80%"
      top="5vh"
      :visible.sync="ruleIntroDialog"
    >
      <ruleIntroContent/>
    </el-dialog>
  </div>
</template>
<script>
import { getAppointmentRuleInfoPages,
  deleteAppointmentRuleInfo,
  setCloseAppointmentRuleInfo,
  setOpenAppointmentRuleInfo,
  getCheckRoomList,
  getDepAreaList,
  getItemList,
  getBigPartList,
  getHisCheckroomgetSmallpartlist,
  getDepList,
  getItemGroupList
} from '@/api/api.js'
import { getListByAreaNameFunc } from '@/api/common'
import virtualselect from '@/components/virtualselect/index'
import paginationCont from '@/components/Pagination/index'
import dicDialog from './dicDialog'
// import setRoomDialog from './setRoomDialog'
import { PageStatus, Options } from '@/utils/constant'
import { ruleTypeFlr, ruleStatusFlr } from '@/utils/validate'
import settingDialog from './settingDialog.vue'
import templateFullscheduleDialog from './templateFullscheduleDialog'
// import settingDialogGroup from './settingDialogGroup.vue'
import { dateFormatter } from '@/utils/validate'
import sourceInfoDialog from './sourceInfoDialog.vue'
import ruleIntroContent from './comp/ruleIntro.vue'
import { conditionGroupDefault } from '@/utils/ruleAddDefault'
// import aes from '@/utils/aes'

export default {
  name: 'RulesSetting',
  components: {
    paginationCont,
    dicDialog,
    // setRoomDialog,
    settingDialog,
    templateFullscheduleDialog,
    // settingDialogGroup,
    sourceInfoDialog,
    ruleIntroContent,
    virtualselect
  },
  filters: {
    ruleTypeFlr,
    ruleStatusFlr,
    hospitalCodeFlr: (val, arg1) => {
      if (!val) return ''
      let obj = arg1.find((item) => {
        return item.code === val
      })
      if (obj) {
        return obj.name
      } else {
        return ''
      }
    },
    flrModelTypeText(val) {
      let txt = ''
      const _obj = Options.modelTypeOptions.find(item => item.value === val)
      if (_obj) {
        txt = _obj.label
      }
      return txt
    }
  },
  data() {
    return {
      curDate: dateFormatter(new Date()),
      appoRepair: this.$store.state.user.appoRepair, // 排班模板判断，是否现在时段间隔的时段占位数据
      pageStatus: PageStatus,
      options: Options,
      listQuery: { // 查询字段
        ruleName: '',
        areaName: '',
        depArea: '',
        dep: '',
        checkRoom: '',
        bigpart: '',
        smallpart: '',
        patientType: '',
        appointmentType: '',
        status: -1,
        ruleType: [],
        itemProperty: '', // 项目属性
        hospitalCode: this.$store.state.user.hospitalCode
      },
      itempropertyOptions: [], // 项目属性
      areaNameOptions: [],
      depAreaOptions: [],
      depOptions: [],
      checkRoomOptions: [],
      bigpartOptions: [],
      smallpartOptions: [],
      patientTypeOptions: Options.patientTypeItemOptions.map(item => item.label),
      appointmentTypeOptions: [],
      tableData: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      ruleFormSendData: null,
      curStatus: PageStatus.add, // edit or add
      showRight: false,
      dialogSetRoomVisible: false, // 设置机房
      dialogDicVisible: false, // 数据字典
      controlConditionValue: '', // 控件控制
      conditionSelectValueOptions: [], // 数值选项
      trackIndex: [], // 记录index
      recordString: '', // 记录修改的数值
      loading: false,
      multipleSelection: [],
      showToolBox: false,
      qiyongFlag: false,
      jingyongFlag: false,
      rowData: null,
      infoVisible: false,
      dialogVisible: false,
      infoParams: {},
      ruleIntroDialog: false
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    },
    appConfig() {
      let appConfig = this.$store.state.settings.appConfig
      return appConfig
    },
    batchUpdateAppoScale() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.batchUpdateAppoScale
    }
  },
  watch: {
    multipleSelection(val) {
      if (val && val.length > 1) {
        this.showToolBox = true
        this.qiyongFlag = false
        this.jingyongFlag = false
        val.forEach(el => {
          if (el.status) {
            this.qiyongFlag = true
          } else {
            this.jingyongFlag = true
          }
        })
      } else {
        this.showToolBox = false
      }
    }
    /* 'ruleForm.ruleType': {
      handler(val) {
        if (val) {
          let category = this.checkCategory()
          let obj = {
            name: '检查类型',
            checkType: [],
            filterText: '',
            ref: 'tree1',
            checkTypeData: JSON.parse(JSON.stringify(this.checkTypeData))
          }
          if (this.treeList.length > 1) {
            this.treeList.splice(1)
          }
          if (category === 1) {
            this.treeList[0].name = '检查类型'
          } else if (category === 3) {
            obj.name = '前置检查内容'
            obj.ref = 'tree' + category
            this.treeList[0].name = '检查类型'
            this.treeList.push(obj)
          } else if (category === 4) {
            obj.name = '排斥检查类型'
            obj.ref = 'tree' + category
            this.treeList[0].name = '检查类型'
            this.treeList.push(obj)
          } else if (category === 5) {
            obj.name = '2类检查类型'
            obj.ref = 'tree' + category
            this.treeList[0].name = '1类检查类型'
            this.treeList.push(obj)
          }
        }
      }
    },
    curStatus(val) {
      if (val && val === this.pageStatus.add) {
        let obj = {
          name: '检查类型',
          checkType: [],
          filterText: '',
          num: '1',
          checkTypeData: JSON.parse(JSON.stringify(this.checkTypeData))
        }
        this.treeList.push(obj)
      }
    } */
  },
  created() {
    this.$getHospitalList()
    this.init()
    // this.fetchData()
  },
  methods: {
    silu() {
      /**
           * 多棵树的实现思路
           *  监听curState === 新增，就往this.treeList push 整个树对象 根据ruleType 来区分push几个对象（对象记得改name属性） （num 这个属性是用来区分不同树的，前两个树固定为1和2）
           * ruleType绑定change事件 值改变就根据值来改变this.treeList的数组（重新push 对象）
           * 每一颗树的handleCheckChange(obj.num,$event)传num值
           * handleCheckChange 方法里处理好的数据赋值给this.treeCheckData对象，结构{num:[,,,,]} 属性名为num
           * 保存的时候根据树对象里的num来取对应的值，把所有值都赋值给this.ruleForm.ruleTypes
           *
           * 编辑的时候等后台拿到检查类型的list后 处理出numList(结构：[1,2,5,6,9]) 根据numList和ruleType 给this.treeList赋值
           * 然后循环 numList 调用 this.checkTreeRow(num) 给每棵树赋值 并处理数据赋值给this.treeCheckData
           * 保存的时候同新增
           *
           */
    },
    ruleTypeFlr(val) {
      return ruleTypeFlr(val)
    },
    init() {
      this.listQuery.hospitalCode = this.$store.state.user.hospitalCode || ''
      try {
        this.getAreaNameList()
        this.getDepAreaOptions()
        this.getCallRoomOptions()
        this.getScheduledDepOptions()
        this.getTypeOptions()
        this.getBigPartOptions()
        this.getSmallPartOptions()
        this.getItempropertyOptions()
      } catch (error) {
        console.error(error)
      }
      this.fetchData()
    },
    async hospitalChange() {
      this.handleCancel()
      try {
        this.search()
      } catch (error) {
        this.tableData = []
        this.totalCount = 0
        this.currentPage = 1
        console.warn(error)
      }
    },
    getAreaNameList() {
      const params = {
        HospitalCode: this.listQuery.hospitalCode
      }
      getListByAreaNameFunc(params).then(res => {
        this.areaNameOptions = res
      })
    },
    getItempropertyOptions() {
      /* 项目属性列表 */
      let params = {
        hospitalCode: this.listQuery.hospitalCode,
        Type: '项目属性'
      }
      return new Promise(resolve => {
        getItemGroupList(params).then((res) => {
          if (res.code === 10000) {
            this.itempropertyOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getDepAreaOptions() {
      /* 影像区域列表 */
      return getDepAreaList({ hospitalCode: this.listQuery.hospitalCode, areaName: this.listQuery.areaName }).then(res => {
        if (res.code === 10000) {
          this.depAreaOptions = res.content.list
          return res
        }
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.listQuery.hospitalCode,
        areaName: this.listQuery.areaName,
        depArea: this.listQuery.depArea
      }
      return getDepList(params).then((res) => {
        if (res.code === 10000) {
          this.depOptions = res.content.list
          return res
        }
      })
    },
    getCallRoomOptions() {
      /* 检查机房列表 */
      let params = {
        hospitalCode: this.listQuery.hospitalCode,
        areaName: this.listQuery.areaName,
        depArea: this.listQuery.depArea,
        dep: this.listQuery.dep
      }
      return getCheckRoomList(params).then((res) => {
        if (res.code === 10000) {
          this.checkRoomOptions = res.content.list
          return res
        }
      })
    },
    getTypeOptions() {
      const data = {
        HospitalCode: this.listQuery.hospitalCode,
        type: '预约来源'
      }
      return getItemList(data).then(res => {
        if (res.code === 10000) {
          const appointmentTypeOptions = res.content.list.map(_item => _item.item)
          this.appointmentTypeOptions = appointmentTypeOptions
          return res
        }
      })
    },
    getBigPartOptions() {
      const params = {
        hospitalCode: this.listQuery.hospitalCode,
        Dep: this.listQuery.dep
      }
      return new Promise(resolve => {
        getBigPartList(params).then(res => {
          if (res.code === 10000) {
            this.bigpartOptions = res.content.list
          }
          resolve(res)
        })
      })
    },
    getSmallPartOptions() {
      const params = {
        hospitalCode: this.listQuery.hospitalCode,
        Bigpart: this.listQuery.bigpart,
        Dep: this.listQuery.dep
      }
      return new Promise(resolve => {
        getHisCheckroomgetSmallpartlist(params).then(res => {
          if (res.code === 10000) {
            const checkposOptions = res.content.list
            let resultCheckPosOption = []
            checkposOptions.forEach(item => {
              let checkPosItem = {}
              checkPosItem.value = item
              checkPosItem.label = item
              resultCheckPosOption.push(checkPosItem)
            })
            this.smallpartOptions = resultCheckPosOption
            // console.log('this.checkposOptions', this.checkposOptions)
          }
          resolve(res)
        })
      })
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.appointmentTypeOptions = []
          this.itempropertyOptions = []
          this.depAreaOptions = []
          this.depOptions = []
          this.checkRoomOptions = []
          this.bigpartOptions = []
          this.smallpartOptions = []
          this.areaNameOptions = []
          this.listQuery.bigpart = ''
          this.listQuery.depArea = ''
          this.listQuery.dep = ''
          this.listQuery.checkRoom = ''
          this.listQuery.appointmentType = ''
          this.listQuery.smallpart = ''
          this.listQuery.areaName = ''
          this.listQuery.itemproperty = ''
          try {
            await this.getDepAreaOptions()
            this.getAreaNameList()
            this.getScheduledDepOptions()
            this.getCallRoomOptions()
            this.getTypeOptions()
            this.getItempropertyOptions()
            this.search()
            this.getBigPartOptions()
            this.getSmallPartOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'areaName':
          this.depAreaOptions = []
          this.depOptions = []
          this.checkRoomOptions = []
          this.bigpartOptions = []
          this.smallpartOptions = []
          this.listQuery.bigpart = ''
          this.listQuery.depArea = ''
          this.listQuery.dep = ''
          this.listQuery.checkRoom = ''
          this.listQuery.smallpart = ''
          try {
            await this.getDepAreaOptions()
            this.getScheduledDepOptions()
            this.getCallRoomOptions()
            this.getTypeOptions()
            // this.search()
            this.getBigPartOptions()
            this.getSmallPartOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'depArea':
          this.depOptions = []
          this.checkRoomOptions = []
          this.listQuery.dep = ''
          this.listQuery.checkRoom = ''
          try {
            await this.getScheduledDepOptions()
            this.getCallRoomOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'dep':
          this.checkRoomOptions = []
          this.bigpartOptions = []
          this.smallpartOptions = []
          this.listQuery.bigpart = ''
          this.listQuery.checkRoom = ''
          this.listQuery.smallpart = ''
          try {
            await Promise.all([
              this.getCallRoomOptions(),
              this.getBigPartOptions(),
              this.getSmallPartOptions()
            ])
          } catch (err) {
            console.log(err)
          }
          break
        case 'bigpart':
          this.listQuery.smallpart = ''
          this.smallpartOptions = []
          try {
            this.getSmallPartOptions()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    fetchData() {
      this.loading = true
      const RuleType = this.listQuery.ruleType.join(',')
      // console.log('this.listQuery.status====>', this.listQuery.status)
      let data = {
        HospitalCode: this.listQuery.hospitalCode,
        RuleName: this.listQuery.ruleName,
        Status: this.listQuery.status,
        areaName: this.listQuery.areaName,
        depArea: this.listQuery.depArea,
        dep: this.listQuery.dep,
        checkRoom: this.listQuery.checkRoom,
        appointmentType: this.listQuery.appointmentType,
        patientType: this.listQuery.patientType,
        bigpart: this.listQuery.bigpart,
        smallpart: this.listQuery.smallpart,
        RuleType: RuleType || '',
        pageSize: this.pageSize, // 页面大小
        pageNumber: this.currentPage, // 页码
        itemProperty: this.listQuery.itemProperty
      }
      this.tableData = []
      this.totalCount = 0
      getAppointmentRuleInfoPages(data).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.tableData = res.content.list
          this.totalCount = res.content.totalCount
        }
      }).catch(() => {
        this.loading = false
      })
    },
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    resetParam() {
      this.listQuery.ruleType = []
      this.listQuery.ruleName = ''
      this.listQuery.status = -1
      this.listQuery.areaName = ''
      this.listQuery.depArea = ''
      this.listQuery.dep = ''
      this.listQuery.checkRoom = ''
      this.listQuery.bigpart = ''
      this.listQuery.smallpart = ''
      this.listQuery.appointmentType = ''
      this.listQuery.itemProperty = ''
      this.listQuery.patientType = ''
      this.fetchData()
    },
    // 获取右边form
    getRightPanel(status, params) {
      console.log('所要编辑的Item', params)
      if (status === this.pageStatus.edit && params) {
        this.$refs.table.setCurrentRow(params)
        this.rowData = params
      } else {
        // 如果是新增按钮 重置form
        // 打开左侧弹窗前清空树勾选
        this.$nextTick(() => {
          this.$refs.settingDialog.handleReset()
        })
        this.rowData = null
      }
      this.curStatus = status
      this.showRight = true
    },
    // 打开新增规则，使用默认设置的规则选项
    setPanelDefault() {
      this.$nextTick(() => {
        this.$refs.settingDialog.handleReset()
      })
      this.rowData = {
        id: '',
        ruleContents: [...conditionGroupDefault],
        ruleType: 9
      }
      this.curStatus = this.pageStatus.add
      this.showRight = true
    },
    settingRefresh() {
      if (this.rowData && this.rowData.id) {
        // 编辑，重新请求数据
        this.fetchData()
      } else {
        this.search()
      }
    },
    openInfoDialog(hospitalCode, id) {
      this.infoParams = { hospitalCode: hospitalCode, id }
      this.infoVisible = true
    },
    handleCancel() {
      // 关闭右侧弹窗
      this.showRight = false
    },
    handleLock(row) {
      let tip = row.status ? '禁用' : '启用'
      this.$confirm(`此操作将${tip}该规则, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.lockData(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    lockData(row) {
      let data = {
        id: row.id,
        hospitalCode: row.hospitalCode
      }
      if (row.status) {
        // 进行禁用
        setCloseAppointmentRuleInfo(data).then(res => {
          // 改掉列表的数据
          if (res && res.code === 10000) {
            this.fetchData()
            this.$message.success('已经成功禁用')
            /* if (this.rowData && this.rowData.id === row.id) {
              this.$refs.settingDialog.changeBatch(0)
            } */
          }
        })
      } else {
        // 进行启用
        setOpenAppointmentRuleInfo(data).then(res => {
          // 改掉列表的数据
          if (res && res.code === 10000) {
            this.fetchData()
            this.$message.success('已经成功启用')
            /*  if (this.rowData && this.rowData.id === row.id) {
              this.$refs.settingDialog.changeBatch(1)
            } */
          }
        })
      }
    },
    handleDelete(i, row) {
      let confirmMsg = '此操作将永久删除该规则, 是否继续?'
      if (this.rowData && this.rowData.id === row.id) {
        confirmMsg = '该条规则正在编辑, 是否删除?'
      }
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData(row) {
      // 清空右边
      let data = {
        id: row.id,
        hospitalCode: row.hospitalCode
      }
      deleteAppointmentRuleInfo(data).then(res => {
        if (res && res.code === 10000) {
          // 删除左边
          this.search()
          this.$message.success('删除成功')
          if (this.rowData.id === row.id) {
            this.handleCancel()
          }
        }
      })
    },
    handleSetRoom() {
      // this.dialogSetRoomVisible = true
      if (this.$refs.templatefullscheduledialog) {
        this.$refs.templatefullscheduledialog.init([], this.curDate)
      }
    },
    handleDicDialog() {
      this.dialogDicVisible = true
      // getItemDicPages().then(res=>{
      //   if(res && res.code === 10000){
      //     this.tableDic = res.content.list
      //   }
      // })
    },
    handleDicClose() {
      this.dialogDicVisible = false
      // 获取规则配置（数据字典内容）
      this.$refs.settingDialog.getItemList()
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 格式化医院code
    frtHospCode(row, column, cellValue, index) {
      let name = ''
      let hospIndex = this.mx_hospitalList.findIndex(item => item.code === cellValue)
      if (hospIndex !== -1) {
        name = this.mx_hospitalList[hospIndex].name
      }
      return name
    },
    frtTime(row, column, cellValue, index) {
      let time = ''
      if (cellValue) {
        time = cellValue.slice(0, 10)
      }
      return time
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    cancleChoose() {
      // 取消选择
      this.multipleSelection = []
      this.$refs.table.clearSelection()
    },
    batchSetStatus() {
      // 批量禁用
      let tip = this.multipleSelection[0].status ? '禁用' : '启用'
      this.$confirm(`此操作将批量${tip}规则, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let successNum = 0
        let faliNum = 0
        for (let v of this.multipleSelection) {
          //   this.lockData(v)
          let data = {
            hospitalCode: v.hospitalCode,
            id: v.id
          }
          if (v.status) {
            // 进行禁用
            await setCloseAppointmentRuleInfo(data).then(res => {
              // 改掉列表的数据
              if (res && res.code === 10000) {
                successNum++
              } else {
                faliNum++
              }
            })
          } else {
            // 进行启用
            await setOpenAppointmentRuleInfo(data).then(res => {
              // 改掉列表的数据
              if (res && res.code === 10000) {
                successNum++
              } else {
                faliNum++
              }
            })
          }
        }

        this.fetchData()
        this.$message.success(`已经成功${tip}` + successNum + '条,失败' + faliNum + '条')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    batchDelete() {
      // 批量删除
      let confirmMsg = '此操作将永久批量删除该选中机房, 是否继续?'
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          let successNum = 0
          let faliNum = 0
          for (let v of this.multipleSelection) {
            let data = {
              hospitalCode: v.hospitalCode,
              id: v.id
            }
            await deleteAppointmentRuleInfo(data).then(res => {
              if (res && res.code === 10000) {
                successNum++
              } else {
                faliNum++
              }
            })
          }
          this.search()
          this.$message.success(`已经成功删除` + successNum + '条,失败' + faliNum + '条')
        } catch (error) {
          console.error(error)
        }
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    openHelper() {
      this.dialogVisible = true
      /*  let docx = require('docx-preview')
      const xhr = new XMLHttpRequest()
      xhr.open('get', '/static/file/ruleDescription.docx', true)
      xhr.responseType = 'blob'
      xhr.onload = () => {
        if (xhr.status === 200) {
          let blob = xhr.response
          docx.renderAsync(blob, this.$refs.docxFile) // 渲染到页面预览
        }
      }
      xhr.send() */
    },
    download() {
      // 下载
      var a = document.createElement('a') // 创建一个<a></a>标签
      a.href = '/static/file/ruleDescription.pdf'// 将流文件写入a标签的href属性值
      a.download = 'ruleDescription.pdf' // 设置文件名
      a.style.display = 'none' // 障眼法藏起来a标签
      document.body.appendChild(a) // 将a标签追加到文档对象中
      a.click() // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove() // 一次性的，用完就删除a标签
    }
  }

}
</script>
<style lang="scss" scoped>
.notify-dialog {
  /deep/ .el-dialog__body {
    height: 83vh;
    overflow: auto;
    iframe{
        height:calc(100% - 5px);
    }
  }
}
.container{
    min-height: calc(100vh - 50px);
    .header-section{
        padding: 16px;
        margin-bottom: 10px;
        .click-button{
            width: 80px;
        }
        .param-name_input{
            width: 240px;
                /deep/ .el-input__inner{
                    padding-left:30px
                }
        }
        .param-type_input{
            width: 160px;
        }
        .el-form-item{
            margin-bottom: 0px;
            /* margin-right: 20px; */
            /* margin-left: 25px; */
        }
    }
  .col-left{
    padding: 15px;

  }
  .icon{
    margin-right: 4px;
  }
  .blue-color{
      color:#0093FF
  }
  .content-section{
    height: calc(100% - 103px);
    overflow: auto;
    .warning-color{
        color:#ff7600;
    }
    .success-color{
        color:#67C23A;
    }
    .content-title{
        margin: 10px 20px 0;
        span{
            font-size: 16px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 600;
        }
    }
    .span-border{
        border-right: 1px solid #D8D8D8;
    }
    .tools-span{
        padding: 0 10px;
        cursor: pointer;
    }
    .primary{
        color:#1890FF
    }
    .error{
        color:#EB4F4F
    }
  }
  .ddt-title{
    padding: 15px;
    width: 100%;
    line-height: 18px;
    font-size: 16px;
    .red-text{
        color:red
    }
}

  .toolBox{
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #E5E7EC;
        padding: 12px 28px;
        position: fixed;
        bottom: 0;
        background: #fff;
        z-index: 10;
        margin-left: -20px;
        .toolBox-text{
            margin-left: 8px;
            font-size: 13px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.65);
            span{
                margin:0 4px;
            }
        }
        .cancle-click{
            cursor: pointer;
            font-size: 13px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #919398;
            margin-left: 32px;
        }
  }
  .toolBox-small{
      width: calc(100% - 210px);
  }
  .toolBox-midul{
      width: calc(100% - 54px);
  }
  .toolBox-large{
      width: 100%
  }
}
.el-input{
  width:auto;
  .el-input__suffix-inner span{
        color: #606266;
  }
}

</style>
